package com.hanlin.beforejavacodesummary.yanshi;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class LazyImageStreamReader {
    
    private static final ObjectMapper objectMapper = new ObjectMapper();
    private final List<ImageInfo> imageInfoList;
    
    public LazyImageStreamReader(String jsonData) throws IOException {
        this.imageInfoList = parseImageInfo(jsonData);
    }
    
    /**
     * 解析 JSON 获取图片信息（不立即创建流）
     */
    private List<ImageInfo> parseImageInfo(String jsonData) throws IOException {
        List<ImageInfo> infoList = new ArrayList<>();
        JsonNode rootNode = objectMapper.readTree(jsonData);
        
        if (rootNode.isArray()) {
            for (JsonNode node : rootNode) {
                if (node.has("resultImg")) {
                    String imageUrl = node.get("resultImg").asText();
                    String pointName = node.has("pointName") ? node.get("pointName").asText() : "未知";
                    String time = node.has("time") ? node.get("time").asText() : "";
                    String result = node.has("result") ? node.get("result").asText() : "";
                    
                    infoList.add(new ImageInfo(imageUrl, pointName, time, result));
                }
            }
        }
        
        return infoList;
    }
    
    /**
     * 获取所有图片信息
     */
    public List<ImageInfo> getAllImageInfo() {
        return new ArrayList<>(imageInfoList);
    }
    
    /**
     * 根据索引获取图片 InputStream
     */
    public InputStream getImageStream(int index) throws IOException {
        if (index < 0 || index >= imageInfoList.size()) {
            throw new IllegalArgumentException("索引越界: " + index);
        }
        
        ImageInfo info = imageInfoList.get(index);
        return createImageStream(info.getImageUrl());
    }
    
    /**
     * 获取指定图片 URL 的 InputStream
     */
    public InputStream getImageStream(String imageUrl) throws IOException {
        return createImageStream(imageUrl);
    }
    
    /**
     * 创建图片流
     */
    private InputStream createImageStream(String imageUrl) throws IOException {
        URL url = new URL(imageUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(10000);
        connection.setReadTimeout(30000);
        
        int responseCode = connection.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK) {
            connection.disconnect();
            throw new IOException("HTTP response code: " + responseCode);
        }
        
        return connection.getInputStream();
    }
    
    /**
     * 使用示例
     */
    public static void main(String[] args) {
        try {
            String jsonData = "[{...}]"; // 你的 JSON 数据
            
            LazyImageStreamReader reader = new LazyImageStreamReader(jsonData);
            List<ImageInfo> allImages = reader.getAllImageInfo();
            
            System.out.println("找到 " + allImages.size() + " 张图片");
            
            // 逐个处理图片流
            for (int i = 0; i < allImages.size(); i++) {
                ImageInfo info = allImages.get(i);
                System.out.println("处理图片: " + info.getPointName());
                
                try (InputStream imageStream = reader.getImageStream(i)) {
                    // 处理 InputStream
                    processImageStream(imageStream, info);
                } catch (IOException e) {
                    System.err.println("处理图片失败: " + info.getImageUrl() + " - " + e.getMessage());
                }
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    private static void processImageStream(InputStream imageStream, ImageInfo info) throws IOException {
        // 示例：将流保存到文件
        // Files.copy(imageStream, Path.of("images/" + info.getPointName() + ".jpg"));
        
        // 或者进行其他处理
        System.out.println("正在处理: " + info.getPointName() + " - " + info.getTime());
    }
}

/**
 * 图片信息类
 */
class ImageInfo {
    private final String imageUrl;
    private final String pointName;
    private final String time;
    private final String result;
    
    public ImageInfo(String imageUrl, String pointName, String time, String result) {
        this.imageUrl = imageUrl;
        this.pointName = pointName;
        this.time = time;
        this.result = result;
    }
    
    // Getter 方法
    public String getImageUrl() { return imageUrl; }
    public String getPointName() { return pointName; }
    public String getTime() { return time; }
    public String getResult() { return result; }
}